local BaseData = require("data.base.BaseData")
local HeroData = class("HeroData", BaseData)
local StoreConst = require("const.StoreConst")
local HeroUnitData = require("data.HeroUnitData")

local schema = {}

HeroData.schema = schema

function HeroData:ctor()
    HeroData.super.ctor(self)
end

function HeroData:init()
    self:_initData()
end

function HeroData:_initData()
    self._heroList = {}
    self._globalid = G_StoreManager:getGlobalId(StoreConst.HERO_GLOBALID) or 0
    local list = G_StoreManager:getDataList(StoreConst.HEROS)
    for i = 1, #list do
        self:_setUnitData(list[i])
    end
end

function HeroData:_setUnitData(data)
    local unit = self._heroList["k_" .. data.id]
    if not unit then
        unit = HeroUnitData.new()
        self._heroList["k_" .. data.id] = unit
    end
    unit:update(data)
end

function HeroData:save()
    local result = {}
    for _, unit in pairs(self._heroList) do
        local param = unit:getPureParam()
        table.insert(result, param)
    end
    G_StoreManager:setDataList(StoreConst.HEROS, result)
    G_StoreManager:setGlobalId(StoreConst.HERO_GLOBALID, self._globalid)
end

function HeroData:getUnitById(id)
    return self._heroList["k_" .. id]
end

function HeroData:addData(baseId)
    self._globalid = self._globalid + 1
    local data = {}
    data.id = self._globalid
    data.base_id = baseId
    data.level = 1
    self:_setUnitData(data)
end

function HeroData:getHeroList()
    local result = {}
    for _, unit in pairs(self._heroList) do
        table.insert(result, unit)
    end
    return result
end

function HeroData:getHeroListNoBattle()
    local result = {}
    for _, unit in pairs(self._heroList) do
        if not unit:isInBattle() then
            table.insert(result, unit)
        end
    end
    return result
end

function HeroData:upgradeHero(heroId, exp)
    local HeroDataHelper = require("data.helper.HeroDataHelper")
    local ErrorCodeConst = require("const.ErrorCodeConst")
    local unit = self:getUnitById(heroId)
    local level = unit:getLevel()
    if level >= unit:getConfig().lv_max then
        return ErrorCodeConst.ERROR_LEVEL_MAX
    end
    local curExp = unit:getExp()
    local maxExp = HeroDataHelper.getHeroCurMaxExp(unit)
    curExp = curExp + exp
    if curExp >= maxExp then
        while (curExp > 0) do
            curExp = curExp - maxExp
            local curLevel = unit:getLevel()
            local nextLevel = curLevel + 1
            unit:setLevel(nextLevel)
            if curExp > maxExp then
                unit:setExp(0)
                maxExp = HeroDataHelper.getHeroCurMaxExp(unit)
            else
                unit:setExp(curExp)
                curExp = 0
            end
        end
    else
        unit:setExp(curExp)
    end
    return true
end

return HeroData
